from flask_sqlalchemy import SQLAlchemy as _SQLAlchemy
from flask import current_app, flash
from flask_migrate import Migrate
from flask_login import LoginManager
from flask_bootstrap import Bootstrap
from flask_wtf import CSRFProtect
from flask_ckeditor import CKEditor
from flask_cors import CORS
from flask_moment import Moment
from contextlib import contextmanager


class SQLAlchemy(_SQLAlchemy):
    @contextmanager
    def auto_commit(self):
        try:
            yield
            self.session.commit()
        except Exception as e:
            self.session.rollback()
            current_app.logger.error(e)
            flash('未执行成功，请联系管理员', 'danger')
            raise e


db = SQLAlchemy()
migrate = Migrate()
cors = CORS()
csrf = CSRFProtect()
ckeditor = CKEditor()
login_manager = LoginManager()
bootsrtap = Bootstrap()
moment = Moment()
